package com.wocharging.wxapp.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wocharging.base.domain.WoWxUser;
import com.wocharging.base.mapper.WoWxUserMapper;
import com.wocharging.wxapp.result.Result;
import com.wocharging.wxapp.service.WxAppService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WxAppServiceImpl implements WxAppService {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private WoWxUserMapper woWxUserMapper;

    @Override
    public Result<String> login(String code) {
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
           e.printStackTrace();
           return Result.error(e.getMessage());
        }
        String openId = session.getOpenid();
        // 可以根据 openId 来查询用户信息，并进行登录操作
        // ...
        LambdaQueryWrapper<WoWxUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WoWxUser::getOpenId,openId);
        WoWxUser woWxUser = woWxUserMapper.selectOne(lqw);
        if(ObjUtil.isNull(woWxUser)){
            // 注册用户
        }

        // 签发token
        return Result.success(code);
    }
}
